package com.feilong.edgeAI.utils;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Environment;
import android.util.Log;

import com.feilong.edgeAI.R;

import java.io.File;
import java.io.IOException;
import java.util.Random;

/**
 * Created by【仿脑科技】
 *
 * @Author: potato
 * @CreateDate: 2023/11/7 18:33
 */
public class MusicPlayer implements MediaPlayer.OnPreparedListener,MediaPlayer.OnCompletionListener{
    private static MediaPlayer mediaPlayer;

    public static String XXZ_DIR="/exagear/XXZ/";
    public static String MUSIC_DIR=XXZ_DIR+"musics/";
    public static String SLEEP_DIR=XXZ_DIR+"sleep/";
    private Context context;
    public MusicPlayer(Context context){
        this.context = context;
        mediaPlayer = new MediaPlayer();
    }

    public static String getMusic(String name){
        String path = Environment.getExternalStorageDirectory().getAbsolutePath()+MUSIC_DIR+name+".mp3";
        File file = new File(path);
        if(file.exists()){
            return file.getAbsolutePath();
        }
        return null;
    }
    public static String getSleepMusic(){
        Random random = new Random();
        int number = random.nextInt(4) + 1;
        String path = Environment.getExternalStorageDirectory().getAbsolutePath()+SLEEP_DIR+number+".mp3";
        File file = new File(path);
        if(file.exists()){
            return file.getAbsolutePath();
        }
        return null;
    }
    public void play(String name){
        mediaPlayer = new MediaPlayer();
        int res = R.raw.music;
        if(name.contains("一生所爱")){
//            res = R.raw.yssa;
        }
        AssetFileDescriptor afd = context.getResources().openRawResourceFd(res);
        try {
            mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            afd.close();
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (Exception e) {
            mediaPlayer.release();
            e.printStackTrace();
        }
    }
    public void playLocalMusic(String path){
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                return true;
            }
        });
        try {
            mediaPlayer.setOnCompletionListener(this);
            mediaPlayer.setOnPreparedListener(this);
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepare();
            mediaPlayer.start();
            new Thread(new SeekBarThread()).start();
            isStop = false;
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
    public void playAlarm(){
        mediaPlayer = new MediaPlayer();
        int res = R.raw.burglar_alarm;
        AssetFileDescriptor afd = context.getResources().openRawResourceFd(res);
        try {
            mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            afd.close();
            mediaPlayer.setLooping(true);
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (Exception e) {
            mediaPlayer.release();
            e.printStackTrace();
        }
    }
    private boolean isStop;
    public void stop(){
        isStop = true;
        try {
            if(mediaPlayer!=null&&mediaPlayer.isPlaying()){
                mediaPlayer.stop();
                mediaPlayer.release();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public void pause(){
        isStop = true;
        try {
            if(mediaPlayer!=null&&mediaPlayer.isPlaying()){
                mediaPlayer.pause();
//                mediaPlayer.release();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public void resume(){
        try {
            isStop = false;
            if(mediaPlayer!=null&&!mediaPlayer.isPlaying()){
                new Thread(new SeekBarThread()).start();
                mediaPlayer.start();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public void setProgress(int progress){
        if(mediaPlayer!=null){
            mediaPlayer.seekTo(progress*duration/100);
        }
    }
    public boolean isPlaying(){
       /* try {
            if(mediaPlayer!=null){
                return mediaPlayer.isPlaying();
            }
        }catch (Exception e){
            e.printStackTrace();
        }*/
        return isStop;
    }
    @Override
    public void onPrepared(MediaPlayer mp) {
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        isStop = true;
        if(null!=onMusicPlayListener){
            onMusicPlayListener.onCompletion();
            Log.d(TAG, "onCompletion: ");
        }
    }

    public interface OnMusicPlayListener{
        void onProgress(int progress);
        void onCompletion();
    }
    private OnMusicPlayListener onMusicPlayListener;

    public void setOnMusicPlayListener(OnMusicPlayListener onMusicPlayListener) {
        this.onMusicPlayListener = onMusicPlayListener;
    }

    private static final String TAG = "music";
    private int duration;
    private class SeekBarThread implements Runnable {

        @Override
        public void run() {
            while (mediaPlayer != null && isStop == false) {
                // 将SeekBar位置设置到当前播放位置
                try {
                    // 每100毫秒更新一次位置
                    Thread.sleep(100);
                    if(null!=onMusicPlayListener&&null!=mediaPlayer){
                        duration = mediaPlayer.getDuration();
                        int currentPosition = mediaPlayer.getCurrentPosition();
                        Log.d(TAG, "run: duration"+duration+"  currentPosition="+currentPosition);
                        if(duration!=0){
                            int progress = currentPosition*100/duration;
                            onMusicPlayListener.onProgress(progress);
                        }
                    }
                } catch (Exception e) {
                    isStop = true;
                    e.printStackTrace();
                }
            }

        }
    }
}
